# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base
class Login(Base):

    @view_config(route_name='AppLoginRoute', renderer='../../templates/AppLogin.pt')
    def AppLoginRoute(self):
        return ''

    #@view_config(route_name='AppLoginRoute', render='json', request_method='GET')
    @view_config(route_name='AppLoginVerifyRoute', request_method='POST')
    def AppLoginVerifyRoute(self):
        postParams =  self.request.POST
        tel = postParams.getone('tel')
        password = postParams.getone('password')
        password_digest = HashUtil.getStringMD5(password)
        log.debug('[LOGIN][TEL]' + tel)
        log.debug('[LOGIN][PASSWORD]' + password)
        log.debug('[LOGIN][PASSWORD_DIGEST]' + password_digest)

        sql = "select username, email, tel, type, portrait from user_info where tel = %s and password = %s"
        result = MySqlCRUD.selectImpl(sql, tel, password_digest)
        log.debug(result)
        if result:
            username = result[0]['username']
            email = result[0]['email']
            tel = str(result[0]['tel'])
            userType = str(result[0]['type'])
            portrait = result[0]['portrait']
            timeString = self.getCurrentTimeString();
            tString = base64.b64encode(timeString)
            eString = HashUtil.getStringMD5(tel + tString)
            tokenString = self.calculateToken(tString, tel)
            log.debug('UserName:' + username)
            log.debug('Tel:' + tel)
            log.debug('tString:' + tString)
            log.debug('eString:' + eString)
            log.debug('tokenString:' + tokenString)
            tmpUser = User(username, tel, email, userType, portrait, tString, eString, tokenString)
            map = {'RetCode': '0', 'message': '登录成功!', 'data': tmpUser.__dict__}
            cache = TokenCache()
            cache.addCache(tel, tokenString)
            jsonStr = json.dumps(map, ensure_ascii=False)
            jsonStr = jsonStr.replace('/media', '/static')
            log.debug('[Login]' + jsonStr)
            return Response(jsonStr)
        else:
            tmpUser = User('', '', '', '', '', '', '', '')
            map = {'RetCode': '111', 'message':'手机号或密码错误', 'data': tmpUser.__dict__}
            jsonStr = json.dumps(map, ensure_ascii=False)
            return Response(jsonStr)

    @view_config(route_name='AppQLoginVerifyRoute', request_method='POST')
    def AppQLoginVerifyRoute(self):
        postParams =  self.request.POST
        tel = postParams.getone('tel')
        tString = postParams.getone('tString')
        eString = postParams.getone('eString')
        tokenString = postParams.getone('tokenString')

        log.debug('[QLOGIN][PRE][TEL]' + tel)
        log.debug('[QLOGIN][PRE][T_STRING]' + tString)
        log.debug('[QLOGIN][PRE][E_STRING]' + eString)
        log.debug('[QLOGIN][PRE][TOKEN_STRING]' + tokenString)

        tmpTokenString = self.calculateToken(tString, tel)

        cache = TokenCache()
        result = cache.getCache(tel)
        if (not result) or (result <> tokenString):
            tmpUser = User('', '', '', '', '', '', '', '')
            map = {'RetCode': '113', 'message': '快捷登录Token过期!', 'data': tmpUser.__dict__}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            tmpUser = User('', '', '', '', '', '', '', '')
            map = {'RetCode': '112', 'message': '快捷登录Token无效!', 'data': tmpUser.__dict__}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        sql = "select username, email, tel, type, portrait from user_info where tel = %s"
        result = MySqlCRUD.selectImpl(sql, tel)
        if result:
            username = result[0]['username']
            email = result[0]['email']
            tel = str(result[0]['tel'])
            userType = str(result[0]['type'])
            portrait = result[0]['portrait']
            timeString = self.getCurrentTimeString();
            tString = base64.b64encode(timeString)
            eString = HashUtil.getStringMD5(tel + tString)
            tokenString = self.calculateToken(tString, tel)
            log.debug('[QLOGIN][CUR][USERNAME]' + username)
            log.debug('[QLOGIN][CUR][TEL]' + tel)
            log.debug('[QLOGIN][CUR][T_STRING]' + tString)
            log.debug('[QLOGIN][CUR][E_STRING]' + eString)
            log.debug('[QLOGIN][CUR][TOKEN_STRING]' + tokenString)
            tmpUser = User(username, tel, email, userType, portrait, tString, eString, tokenString)
            map = {'RetCode': '0', 'message': '快捷登录成功!', 'data': tmpUser.__dict__}
            cache = TokenCache()
            cache.addCache(tel, tokenString)
            jsonStr = json.dumps(map, ensure_ascii=False)
            jsonStr = jsonStr.replace('/media', '/static')
            log.debug('[QLogin]' + jsonStr)
            return Response(jsonStr)

    @view_config(route_name='AppIndexRoute', renderer='../templates/AppIndex.pt')
    def AppIndexRoute(self):
        print self.request.session
        if self.request.session:
            pass
        else:
            return HTTPFound(location='/AppLogin')
        return {'name': self.request.session['username']}

    @view_config(route_name='AppChecksumRoute', request_method='POST')
    def AppChecksumRoute(self):
        postParams =  self.request.POST
        tel = postParams.getone('tel')
        tString = postParams.getone('tString')
        eString = postParams.getone('eString')
        tokenString = postParams.getone('tokenString')

        log.debug('[CHECKSUM][TEL]' + tel)
        log.debug('[CHECKSUM][T_STRING]' + tString)
        log.debug('[CHECKSUM][E_STRING]' + eString)
        log.debug('[CHECKSUM][TOKEN_STRING]' + tokenString)

        tmpTokenString = self.calculateToken(tString, tel)

        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '请重新登录'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        timeString = str(time.time())
        cache = ChecksumCache()
        if not cache.addCache(tel, timeString):
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '重新提交请求'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        map = {'RetCode': '0', 'message': 'OK!', 'data': timeString}
        jsonStr = json.dumps(map, ensure_ascii=False)
        log.debug(jsonStr)
        return Response(jsonStr)

    @view_config(route_name='AppRegisterRoute', request_method='POST')
    def AppRegisterRoute(self):
        postParams = self.request.POST
        tel = postParams.getone('tel')
        checksum = postParams.getone('cs')
        password = postParams.getone('pw')
        password_digest = HashUtil.getStringMD5(password)
        log.debug('[REGISTER]tel:' + tel)
        log.debug('[REGISTER]password:' + password)
        log.debug('[REGISTER]password_digest:' + password_digest)

        resultTel = self.checkTelAvailable(tel)
        if not resultTel:
            map101 = {'RetCode': '101', 'message':"手机号已被使用", 'data':''}
            jsonStr = json.dumps(map101, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        else:
            checkresult = self.calcSmsCheckSum(tel, checksum)
            if checkresult != 200:
                map102 = {'RetCode': '102', 'message': '短信验证码错误', 'data': str(checkresult)}
                jsonStr = json.dumps(map102, ensure_ascii=False)
                return Response(jsonStr)
            insertSql = '''
                INSERT INTO user_info (user_info.tel, user_info.password, user_info.type, user_info.default)
                    VALUES(%s, %s, %s, %s);
            '''
            resultInsert = MySqlCRUD.insertImpl(insertSql, tel, password_digest, '2', password)
            map0 = {'RetCode': '0', 'message':'注册成功！', 'data':''}
            jsonStr = json.dumps(map0, ensure_ascii=False)
            log.debug(jsonStr)
            return Response(jsonStr)

    @view_config(route_name='AppPwdForgetRoute', request_method='POST')
    def AppPwdForgetRoute(self):
        postParams = self.request.POST
        tel = postParams.getone('tel')
        checksum = postParams.getone('csc')
        password = postParams.getone('data')
        password_digest = HashUtil.getStringMD5(password)
        log.debug('[REGISTER]tel:' + tel)
        log.debug('[REGISTER]password:' + password)
        log.debug('[REGISTER]password_digest:' + password_digest)

        resultTel = self.checkTelAvailable(tel)
        if resultTel:
            map = {'RetCode': '128', 'message':"重置密码失败，原手机号不存在！", 'data':''}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        else:
            checkresult = self.calcSmsCheckSum(tel, checksum)
            if checkresult != 200:
                map102 = {'RetCode': '102', 'message': '短信验证码错误', 'data': str(checkresult)}
                jsonStr = json.dumps(map102, ensure_ascii=False)
                return Response(jsonStr)
            updateSQL = '''
               UPDATE user_info
                SET `password` = %s,
                    `default` = %s
                    WHERE tel = %s;
            '''
            resultUpdate = MySqlCRUD.updateImpl(updateSQL, password_digest, password, tel)
            map = {'RetCode': '0', 'message':'重置密码成功！', 'data':''}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.debug(jsonStr)
            return Response(jsonStr)

